package com.dolphin.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dolphin.base.BaseController;
import com.dolphin.commons.Constants;
import com.dolphin.commons.Pager;
import com.dolphin.commons.ResponseBean;
import com.dolphin.model.Permission;
import com.dolphin.model.Role;
import com.dolphin.model.RolePermission;
import com.dolphin.permission.ApiAuth;
import com.dolphin.service.PermissionService;
import com.dolphin.service.RolePermissionService;
import com.dolphin.service.RoleService;
import com.dolphin.vo.LayuiXTreeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 角色相关
 *
 * @author dolphin
 */
@Controller
@RequestMapping("/admin")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * @return java.lang.String
     * @description 角色管理页
     * @author dolphin
     */
    @GetMapping("/role")
    @ApiAuth(name = "角色管理", groupId = Constants.ADMIN_MENU_GROUP_AUTH, permission = "admin:role:index")
    public String index() {
        return "/static/admin/pages/role/list.html";
    }

    /**
     * @return java.lang.String
     * @description 添加角色
     * @author dolphin
     */
    @GetMapping("/role/addPage")
    @ApiAuth(name = "添加角色", type = Permission.ResType.NAV_LINK, permission = "admin:role:addPage")
    public String addCarouselPage() {
        return "/static/admin/pages/role/add.html";
    }

    /**
     * 编辑角色
     *
     * @return String
     */
    @GetMapping("/role/editPage/{id}")
    @ApiAuth(name = "编辑角色", type = Permission.ResType.NAV_LINK, permission = "admin:role:editPage")
    public String editPage(@PathVariable("id") String id, Model model) {
        Role role = roleService.getRoleById(Long.valueOf(id));
        model.addAttribute("role", role);
        return view("/static/admin/pages/role/edit.html");
    }

    /**
     * 编辑角色权限
     *
     * @return String
     */
    @GetMapping("/role/authPage/{id}")
    @ApiAuth(name = "权限角色", type = Permission.ResType.NAV_LINK, permission = "admin:role:authPage")
    public String authPage(@PathVariable("id") String id, Model model) {
        Role role = roleService.getRoleById(Long.valueOf(id));
        model.addAttribute("role", role);
        List<Permission> all = permissionService.listByMap(Collections.EMPTY_MAP);
        List<Permission> selected = permissionService.selectPermissionByRoleId(Long.parseLong(id));
        List<LayuiXTreeVO> treeList = new ArrayList<>(all.size());
        treeList.addAll(LayuiXTreeVO.transTo(all, res -> res.getName() + "{" + res.getPermissionType() + "}",
                Permission::getId, Permission::getPermissionValue, selected::contains, res -> res.getEnable() == 1));
        List<LayuiXTreeVO> list = LayuiXTreeVO.buildByRecursive(treeList);
        String s = new JSONArray(list).toString();
        model.addAttribute("data", s);
        return view("/static/admin/pages/role/role_menu_list.html");
    }

    /**
     * 更新权限角色
     *
     * @return String
     */
    @PostMapping("/role/updatePermissionByRoleId/{checked}")
    @ResponseBody
    @ApiAuth(name = "更新权限角色", permission = "admin:role:updatePermissionByRoleId")
    public ResponseBean updatePermissionByRoleId(@PathVariable("checked") Boolean checked, @RequestBody RolePermission rolePermission) {
        if (checked) {
            QueryWrapper<RolePermission> userQueryWrapper = new QueryWrapper<>(rolePermission);
            List<RolePermission> list = rolePermissionService.list(userQueryWrapper);
            if (CollectionUtil.isEmpty(list)) {
                rolePermissionService.save(rolePermission);
                return ResponseBean.success("增加成功！", rolePermission);
            }
            return ResponseBean.success("加载成功！", rolePermission);
        } else {
            QueryWrapper<RolePermission> userQueryWrapper = new QueryWrapper<>(rolePermission);
            rolePermissionService.remove(userQueryWrapper);
            return ResponseBean.success("删除成功！", rolePermission);
        }

    }

    /**
     * 批量更新权限角色
     *
     * @return String
     */
    @PostMapping("/role/updatePermissionList/{roleId}")
    @ResponseBody
    @ApiAuth(name = "批量更新权限角色", permission = "admin:role:updatePermissionList")
    public ResponseBean updatePermissionList(@PathVariable("roleId") Long roleId, @RequestBody List<LayuiXTreeVO> layuiXTreeVOs) {
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(roleId);
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>(rolePermission);
        rolePermissionService.remove(queryWrapper);
        if (CollectionUtil.isNotEmpty(layuiXTreeVOs)) {
            List<RolePermission> rolePermissionList = new ArrayList<>();
            getRolePermissionList(layuiXTreeVOs, roleId, rolePermissionList);
            rolePermissionService.saveBatch(rolePermissionList);
        }
        return ResponseBean.success("更新成功！", layuiXTreeVOs);
    }

    private void getRolePermissionList(List<LayuiXTreeVO> layuiXTreeVOs, Long roleId, List<RolePermission> rolePermissionList) {
        layuiXTreeVOs.stream().forEach(x -> {
            if (ObjectUtil.isNotEmpty(x.getValue())) {
                RolePermission rolePermission1 = new RolePermission();
                rolePermission1.setRoleId(roleId);
                rolePermission1.setPermissionId(Long.valueOf(x.getValue()));
                rolePermissionList.add(rolePermission1);
            }
            List<LayuiXTreeVO> children = x.getChildren();
            if (CollectionUtil.isNotEmpty(children)) {
                getRolePermissionList(children, roleId, rolePermissionList);
            }
        });
    }

    /**
     * 获取角色列表（不分页）
     *
     * @return ResponseBean
     */
    @GetMapping("/role/getRoleList")
    @ResponseBody
    @ApiAuth(name = "获取角色列表（不分页）", permission = "admin:role:getRoleList")
    public ResponseBean getRoleList() {
        return ResponseBean.success("获取成功", roleService.getRoleList());
    }

    /**
     * @param pager pager
     * @return
     * @description 角色分页
     * @author dolphin
     */
    @PostMapping("/role/list")
    @ApiAuth(name = "角色分页", permission = "admin:role:list")
    @ResponseBody
    public Pager<Role> list(@RequestBody Pager<Role> pager) {

        return roleService.list(pager);
    }

    /**
     * 添加角色
     *
     * @return String
     */
    @PostMapping("/role/add")
    @ResponseBody
    @ApiAuth(name = "添加角色", permission = "admin:role:add")
    public ResponseBean add(@RequestBody @Valid Role role) {
        try {
            Role oldRole = roleService.getRoleByCode(role.getCode());
            if (oldRole != null) {
                return ResponseBean.fail("角色编码已存在", null);
            }
            roleService.saveOrUpdate(role);
            return ResponseBean.success("添加成功", role);
        } catch (Exception e) {
            return ResponseBean.fail("添加失败", e.getMessage());
        }
    }

    /**
     * 删除角色
     *
     * @return String
     */
    @PostMapping("/role/del")
    @ResponseBody
    @ApiAuth(name = "删除角色", permission = "admin:role:del")
    public ResponseBean del(@RequestBody String id) {

        if (roleService.removeById(id)) {
            return ResponseBean.success("删除成功", null);
        }
        return ResponseBean.fail("删除失败", null);
    }

    /**
     * 更新角色
     *
     * @return String
     */
    @PostMapping("/role/update")
    @ResponseBody
    @ApiAuth(name = "更新角色", permission = "admin:role:update")
    public ResponseBean editcarousel(@RequestBody @Valid Role role) {
        Role oldRole = roleService.getRoleByCode(role.getCode());
        if (oldRole != null && !oldRole.getId().equals(role.getId())) {
            return ResponseBean.fail("角色编码已存在", null);
        }
        if (roleService.updateById(role)) {
            return ResponseBean.success("更新成功", null);
        }
        return ResponseBean.fail("更新失败", null);
    }

    /**
     * 获取权限资源列表
     */
    @GetMapping("/role/authList")
    @ApiAuth(name = "获取权限资源列表", permission = "admin:role:authList")
    @ResponseBody
    public ResponseBean authList(@RequestParam(value = "id") Long id) {
        List<Permission> all = permissionService.listByMap(Collections.EMPTY_MAP);
        List<Permission> selected = permissionService.selectPermissionByRoleId(id);
        List<LayuiXTreeVO> treeList = new ArrayList<>(all.size());
        treeList.addAll(LayuiXTreeVO.transTo(all, Permission::getName, Permission::getId, Permission::getPermissionValue, selected::contains, res -> false));
        List<LayuiXTreeVO> list = LayuiXTreeVO.buildByRecursive(treeList);
        return ResponseBean.success("获取成功", list);
    }
}
